package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Item;
import model.DatabaseException;

/**
 * Servlet implementation class ItemJSON
 */
@WebServlet("/ItemJSON")
public class ItemJSON extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ItemJSON() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		String itemIdString = request.getParameter("itemId");
		String minCountString = request.getParameter("minCount");

		int itemId  = Integer.parseInt(itemIdString);
		int minCount = (minCountString != null)? Integer.parseInt(minCountString) : 0;
		PrintWriter out = response.getWriter();
		try {
			Optional<Item> itemOptional = Item.getItem(itemId,minCount);
			if(itemOptional.isPresent()){
				Item item = itemOptional.get();
				String json = Item.getItemJSON(item);
				out.print(json);
			}else{
				out.print("{}");
			}
			
		} catch (DatabaseException e) {
			out.print("{}");
		}

		
	}

}
